﻿using AutoMapper;
using BW.MesProject.Equipment.Domain.Equipment;
using BW.MesProject.Equipment.Infrastructure.Dto.Input.DeviceType;
using BW.MesProject.Equipment.Infrastructure.Dto.Output.DeviceType;
using BW.MesProject.Equipment.Infrastructure.Equipment;
using BW.MesProject.Public.ErrorCode;
using BW.MesProject.Public.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace BW.MesProject.Equipment.Application.Equipment
{
    /// <summary>
    /// 设备类型服务显示类
    /// </summary>
    public class DeviceTypeService : IDeviceTypeService
    {
        private readonly IBaseRepository<DeviceTypeModel> _deviceTypeRepoistory;
        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数，注入仓储和映射对象
        /// </summary>
        /// <param name="DeviceTypeRepoistory">设备类型仓储</param>
        /// <param name="mapper">AutoMapper 映射对象</param>
        public DeviceTypeService(IBaseRepository<DeviceTypeModel> DeviceTypeRepoistory,IMapper mapper)
        {
            _deviceTypeRepoistory = DeviceTypeRepoistory;
            this._mapper = mapper;
        }

        /// <summary>
        /// 新增设备类型
        /// </summary>
        /// <param name="input">设备类型新增输入参数</param>
        /// <returns>返回操作结果，包含新增设备类型的主键ID</returns>
        public ApiResult<int> AddDeviceType(AddDeviceTypeInput input)
        {
            // 将输入参数映射为设备类型实体
            var data = _mapper.Map<DeviceTypeModel>(input);
            // 判断设备类型名称是否已存在
            if (_deviceTypeRepoistory.GetValue(x => x.DeviceTypeName == input.DeviceTypeName) != null)
            {
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = "设备类型名称已存在",
                    Data = 0
                };
            }
            // 生成雪花ID作为主键
            data.Id = YitIdHelper.NextId();
            // 生成设备类型编码：DT+年月日+4位随机数
            var newCode = "DT" + DateTime.Now.ToString("yyyyMMdd") + new Random().Next(1000, 9999);
            data.DeviceTypeCode = newCode;

            // 添加设备类型到数据库
            var res = _deviceTypeRepoistory.Add(data);
            return new ApiResult<int>
            {
                Code = ApiEnums.Success,
                Message = "新增设备类型成功",
                Data = res,
            };
        }

        /// <summary>
        /// 获取设备类型列表
        /// </summary>
        /// <param name="input">设备类型列表输入参数</param>
        /// <returns>返回设备类型列表</returns>
        public ApiPaging<DeviceTypeOutput> GetDeviceTypeList(DeviceTypeInput input)
        {
            var deviceTypeModel = _deviceTypeRepoistory.GetAll().Where(x => !x.IsDeleted);
            //拼接查询条件
            if (!string.IsNullOrEmpty(input.DeviceTypeName))
            {
                deviceTypeModel = deviceTypeModel.Where(x => x.DeviceTypeName.Contains(input.DeviceTypeName));
            }
            if (!string.IsNullOrEmpty(input.DeviceTypeCode)) 
            {
                deviceTypeModel = deviceTypeModel.Where(x => x.DeviceTypeCode == input.DeviceTypeCode);
            }
            var query= deviceTypeModel.OrderByDescending(x=>x.Id).Skip((input.PageIndex-1)*input.PageSize).Take(input.PageSize).ToList();
            var data = _mapper.Map<List<DeviceTypeOutput>>(query);


            //返回分页结果
            return new ApiPaging<DeviceTypeOutput>
            {
                Code = ApiEnums.Success,
                Message = "获取设备类型列表成功",
                PageData = data,
                TotalCount = deviceTypeModel.Count(),
            };
        }

        /// <summary>
        /// 修改设备类型
        /// </summary>
        /// <param name="input">设备类型修改输入参数</param>
        /// <returns>返回操作结果，包含受影响的行数</returns>
        public ApiResult<int> UpdateDeviceType(UpdateDeviceTypeInput input)
        {
            //根据设备id获取设备类型实体
            var deviceType = _deviceTypeRepoistory.GetValue(x => x.Id == input.Id && !x.IsDeleted);
            //如果设备类型不存在，返回失败结果
            if (deviceType == null)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnums.Fail,
                    Message = "您要修改的设备类型不存在",
                    Data = 0
                };
            }
            deviceType.DeviceTypeDescription = input.DeviceTypeDescription;
            deviceType.DeviceTypeName = input.DeviceTypeName;
            deviceType.UpdatedTime = DateTime.Now;
           
            var model = _deviceTypeRepoistory.GetValue(x => x.DeviceTypeName == input.DeviceTypeName);
            //判断设备类型名称是否已存在
            if (model != null) 
            {
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = "设备类型名称已存在",
                    Data = 0
                };
            }
            //更新设备类型到数据库
            var res = _deviceTypeRepoistory.Update(deviceType);
            //如果更新成功，返回成功结果
            if (res > 0)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnums.Success,
                    Message = "修改设备类型成功",
                    Data = res,
                };
            }
            else
            {
                //如果更新失败，返回失败结果
                return new ApiResult<int>
                {
                    Code = ApiEnums.Fail,
                    Message = "修改设备类型失败",
                    Data = 0
                };
            }
               
        }


        /// <summary>
        /// 逻辑删除设备类型
        /// </summary>
        /// <param name="id">设备类型主键ID</param>
        /// <returns>返回操作结果，包含受影响的行数</returns>
        public ApiResult<int> DeleteDeviceType(long id)
        {
            var entity = _deviceTypeRepoistory.GetValue(x => x.Id == id);
            if (entity == null)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnums.Fail,
                    Message = "设备类型不存在",
                    Data = 0
                };
            }

            entity.IsDeleted = true;
            entity.UpdatedTime = DateTime.Now;

            var res = _deviceTypeRepoistory.Update(entity);

            return new ApiResult<int>
            {
                Code = res > 0 ? ApiEnums.Success : ApiEnums.Fail,
                Message = res > 0 ? "删除设备类型成功" : "删除设备类型失败",
                Data = res
            };
        }

        /// <summary>
        /// 根据设备编号获取设备类型信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ApiResult<DeviceTypeOutput> GetDeviceTypeValue(long id)
        {
            //根据设备编号获取设备类型信息
            var deviceType = _deviceTypeRepoistory.GetValue(x => x.Id == id);

            var data = _mapper.Map<DeviceTypeOutput>(deviceType);
           return new ApiResult<DeviceTypeOutput>
            {
                Code = ApiEnums.Success,
                Message = "获取设备类型信息成功",
                Data = data,
           };
        }
    }
}
